//
//  UseCityVC.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/11/21.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "UseCityVC.h"
#import "TopBackView.h"
#import "CollectionViewCell.h"
#import "RootViewController.h"
 
#import "RLNetworkHelper.h"

@interface UseCityVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic,strong) UICollectionView *collectionView;

@property (nonatomic,strong) NSMutableDictionary *DataDictionary;
//@property (nonatomic,strong) NSMutableArray *dataArray;

@end

@implementation UseCityVC

- (void)viewDidLoad {
    [super viewDidLoad];
    TopBackView *topBackView= [[TopBackView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, 64) title:@"意向方向"];
    
    topBackView.rightButton.hidden = YES;
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:topBackView];
   
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    self.view.backgroundColor = WhiteColor;
    
    self.DataDictionary = [NSMutableDictionary dictionary];
 
    [self initDataSources];
    
    [self initCollectionView];
    
    [self initBtn];
 
    
}

-(void)initDataSources
{
    
    if ([[self.DataDictionary allKeys] count] > 0) {
        [self.DataDictionary removeAllObjects];
    }
    
    
    NSString *urlString = [NSString stringWithFormat:@"%@addr/list",Main_interface];
    
    [Common requestWithUrlString:urlString contentType:application_json errorShow:NO finished:^(id responseObj) {
        
        if ([responseObj[@"success"] boolValue]) {
            
            if ([responseObj[@"data"] count] > 0) {
                
                NSMutableArray *arr = [NSMutableArray array];
                NSMutableArray *arr1 = [NSMutableArray array];

                for (int i = 0; i < [responseObj[@"data"] count]; i ++) {
                    
                    NSMutableDictionary *dic =  [NSMutableDictionary dictionaryWithDictionary: responseObj[@"data"][i]];
                    
                    if ([dic[@"isCheck"] boolValue]) {
                        
                        [dic removeObjectForKey:@"isCheck"];
                        
                        [arr addObject:dic];
                        
                        
                    } else {
                        [dic removeObjectForKey:@"isCheck"];

                        [arr1 addObject:dic];
                        
                    }
                 
                    [self.DataDictionary setObject:arr forKey:@"已选择"];
                    [self.DataDictionary setObject:arr1 forKey:@"未选择"];
                    
                    
                }
                                
                [self.collectionView reloadData];

            }
            
        }
        
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    
}

-(void)initCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(88 * kWidth, 30 * kHeight);
    layout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);

    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, screenWidth, screenHeight - 64 - 70*kHeight) collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    self.collectionView.backgroundColor = WhiteColor;
    self.collectionView.alwaysBounceVertical = YES;
    
    [self.collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"CollectionViewCell"];

    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];

    [self.view addSubview:self.collectionView];
}

-(void)initBtn{
    
    
    UIView * shipBtnView = [[UIView alloc]init];
    shipBtnView.backgroundColor = GrayColor;
    [self.view addSubview:shipBtnView];
    [shipBtnView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(Main_Width, 70*kHeight));
        make.bottom.mas_equalTo(self.view.mas_bottom);
    }];
    
    UIButton * ShipBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [ShipBtn setTitle:@"确定接单" forState:UIControlStateNormal];
    [ShipBtn setTitleColor:WhiteColor forState:UIControlStateNormal];
    [ShipBtn addTarget:self action:@selector(pressShipBtn) forControlEvents:UIControlEventTouchUpInside];
    ShipBtn.layer.cornerRadius = 5;
    ShipBtn.layer.borderWidth = 0.5;
    ShipBtn.layer.borderColor = YellowColor.CGColor;
    ShipBtn.backgroundColor = YellowColor;
    [shipBtnView addSubview:ShipBtn];
    [ShipBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(shipBtnView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(293*kWidth, 40*kHeight));
        make.top.mas_equalTo(shipBtnView.mas_top).with.offset(15*kHeight);
    }];

}

//18518011320
-(void)pressShipBtn{
    
    if ([self.DataDictionary[@"已选择"] count] == 0) {
        
        [WKProgressHUD popMessage:@"请选择常用路线" inView:self.view duration:1.5 animated:YES];
        
    }else{
        
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];

        NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
        [dic setObject:app_Version forKey:@"versionCode"];
    
        NSLog(@"%@",driver_online_Url);
        
        [WKProgressHUD showInView:self.view withText:@"" animated:YES];
        
        [[Common shared] afPostRequestWithUrlString:driver_online_Url parms:nil finishedBlock:^(id responseObj) {
            NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
            NSString * userStatus = [NSString stringWithFormat:@"%@",dic[@"success"]];
            NSLog(@"%@",dic[@"message"]);
            
            [WKProgressHUD dismissAll:YES];
            
            if ([userStatus isEqualToString:@"1"])
            {
                
                
                if (self.callOnlineBack) {
                    self.callOnlineBack(dic);
                }
                
                [self.navigationController popViewControllerAnimated:YES];
                
            }else{
                [WKProgressHUD popMessage:dic[@"message"] inView:self.view duration:1.5 animated:YES];
            }
        } failedBlock:^(NSString *errorMsg) {
            
           
            [WKProgressHUD dismissAll:YES];
            
            [WKProgressHUD popMessage:@"请求超时" inView:self.view duration:1.5 animated:YES];
        }];
        
    }

//    if ([RLNetworkHelper isConnectedToNetwork]) {
//        
//
//    }else{
//        
//        [WKProgressHUD popMessage:@"无网络服务" inView:self.view duration:1.5 animated:YES];
//    }
//
    
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    NSArray *arr = [self.DataDictionary allKeys];
    
    if (arr.count > 0) {

        return  [self.DataDictionary[arr[section]] count];
        
    } else {
        return 0;
    }
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CollectionViewCell *cell = (CollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionViewCell" forIndexPath:indexPath];
    
    cell.label.layer.borderWidth = 0.5;
    cell.label.layer.borderColor = LineGrayColor.CGColor;
    cell.label.font = Font(13);
    NSArray *arr = [self.DataDictionary allKeys];

    cell.label.text = [NSString stringWithFormat:@"%@",self.DataDictionary[arr[indexPath.section]][indexPath.row][@"name"]];
    
    cell.label.layer.cornerRadius = 5 * kHeight;
    cell.label.layer.masksToBounds = YES;
    
    if (indexPath.section == 0) {
        
        cell.label.backgroundColor = YellowColor;
        cell.label.textColor = WhiteColor;
        
    } else {
        cell.label.backgroundColor = WhiteColor;
        cell.label.textColor = BlackColor;
    }
    
    
    return cell;

}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//    [collectionView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
//    CollectionViewCell *cell = (CollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];

    if (indexPath.section == 0) {
        
        //删除
        NSArray *array = self.DataDictionary[@"已选择"];
        
        NSString *string = array[indexPath.row];
        
        NSMutableArray *arr = [NSMutableArray arrayWithArray:array];
        
        [arr removeObjectAtIndex:indexPath.row];
        
        [self.DataDictionary setObject:arr forKey:@"已选择"];
        
        
        NSArray *array1 = self.DataDictionary[@"未选择"];
        NSMutableArray *arr1 = [NSMutableArray arrayWithArray:array1];
        
        [arr1 insertObject:string atIndex:arr1.count];
        
        [self.DataDictionary setObject:arr1 forKey:@"未选择"];
        
        
    } else {
        
        NSArray *array = self.DataDictionary[@"未选择"];
        
        
        NSString *string = array[indexPath.row];
        
        NSMutableArray *arr = [NSMutableArray arrayWithArray:array];
        
        [arr removeObjectAtIndex:indexPath.row];
        
        [self.DataDictionary setObject:arr forKey:@"未选择"];
        
        NSArray *array1 = self.DataDictionary[@"已选择"];
        NSMutableArray *arr1 = [NSMutableArray arrayWithArray:array1];
        
        [arr1 insertObject:string atIndex:arr1.count];
        
        [self.DataDictionary setObject:arr1 forKey:@"已选择"];
        
    }

    [self confirmButton];
}



- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqual:UICollectionElementKindSectionHeader]) {
        
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
        
        
        for (UILabel *view in headerView.subviews) {
            [view removeFromSuperview];
        }
        UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(14, 0, 200, headerView.frame.size.height)];
        lable.font = Font(14);
        lable.textColor = Color_RGB(14, 14, 14, 1);
        
        if (indexPath.section == 0) {
            lable.text = @"已选择";

        } else {
            lable.text = @"未选择";

        }
        
        headerView.backgroundColor = GrayColor;
        
        [headerView addSubview:lable];
        
        return headerView;
    } else {
        return nil;
    }
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(screenWidth, 40);
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    [rootVC setTabBarHidden:YES];
    
}

-(void)confirmButton
{
    
    [WKProgressHUD showInView:self.view withText:@"" animated:YES];
    
    NSArray *postArr = self.DataDictionary[@"已选择"];

    NSData * jsonData = [NSJSONSerialization dataWithJSONObject:postArr options:NSJSONWritingPrettyPrinted error:nil];
    NSString * jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];

    
//    NSString *urlString = [NSString stringWithFormat:@"%@addr/modify",Main_interface];
  
    [[Common shared] afPostRequestWithUrlString:addr_modify parms:@{@"addrs":jsonString} finishedBlock:^(id responseObj) {
        
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObj options:NSJSONReadingMutableLeaves error:nil];
        
        if ([dictionary[@"success"] boolValue]) {
            
            [self initDataSources];
            
            [WKProgressHUD dismissAll:YES];
            
            
        } else {
            
            [WKProgressHUD dismissAll:YES];

            [WKProgressHUD popMessage:dictionary[@"message"] inView:self.view duration:1.5 animated:YES];

            [self initDataSources];
            
            
        }
        
    
    } failedBlock:^(NSString *errorMsg) {
        
        [WKProgressHUD dismissAll:YES];
        
//        [WKProgressHUD popMessage:@"请求超时" inView:self.view duration:1.5 animated:YES];

        NSLog(@"%@",errorMsg);
    }];
    
//    addr/modify  addrs
}


-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
